<template>
    <n-select v-model:value="selectedProductId" filterable placeholder="选择商品" :loading="loading" clearable remote
        :options="options" @search="handleSearch($event, null)" label-field="label" value-field="value"  @update:value="handleClear" />
</template>

<script lang="ts" setup>
import { List } from '@/api/product';
import { NSelect } from 'naive-ui';
import { onMounted, onUnmounted, ref, watch } from 'vue';

// 定义 props
interface Props {
    modelValue: null | number;
    type?: null | number;
}

const props = defineProps<Props>();

// 定义 emits
const emit = defineEmits(['update:modelValue']);

// 定义响应式变量
const selectedProductId = ref(props.modelValue);

const loading = ref(false);
const options = ref<{ label: string; value: number }[]>([]);

// 监听 props 变化
watch(
    () => props.modelValue,
    (newValue) => {
        selectedProductId.value = newValue;
        if (newValue) {
            handleSearch('', newValue);
        }
    }
);

// 监听 selectedProductId 变化并触发事件
watch(
    () => selectedProductId.value,
    (newValue) => {
        console.log(selectedProductId);

        emit('update:modelValue', newValue);
    }
);

// 处理搜索事件
const handleSearch = (keyword: string, id: number | null) => {
    
    loading.value = true;
    List({
        name: keyword,
        id: id,
        type: props.type
    })
        .then((res) => {
            options.value = res?.list?.map(item => ({
                label: props.type === 1 ? item.name + '（' + item.integral + " 积分）" : item.name,
                value: item.id
            })) || [];
        })
        .catch((err) => {
        })
        .finally(() => {
            loading.value = false;
        });
};

const handleClear = (value) => {
    if (value === null) {
        handleSearch('', null); // 清空时执行搜索
    }
};

onMounted(() => {
    console.log(selectedProductId);

    handleSearch('', null);
});

onUnmounted(() => {
    console.log(selectedProductId);
    
    emit('update:modelValue', null);
});
</script>